package com.zjw.touchscreen;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.text.InputFilter;
import android.widget.*;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.PermissionChecker;
import com.zjw.touchscreen.adapter.BluetoothSpinnerAdapter;
import com.zjw.touchscreen.bluetooth.BluetoothUtils;
import com.zjw.touchscreen.listener.*;
import com.zjw.touchscreen.utils.UpdateUtils;

import java.util.concurrent.atomic.AtomicInteger;

@SuppressLint("NewApi")
public class MainActivity extends Activity implements ActivityCompat.OnRequestPermissionsResultCallback {

    private int permissionCount = 0;

    private LinearLayout parent;

    private Spinner spinner;

    private Button connect;

    private ImageView previous;
    private ImageView play;
    private ImageView next;

    private ImageView volumeHigh;
    private ImageView volumelow;
    private ImageView volumeDisable;

    private ImageView menu;
    private ImageView keyboardBounce;
    private ImageView returnKey;

    private ImageView touchBoard;

    private ImageView touchLeft;
    private ImageView touchTop;
    private ImageView touchRight;
    private ImageView touchBottom;

    private EditText editText;

    private SeekBar seekBar;

    private BluetoothSpinnerAdapter bluetoothSpinnerAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        UpdateUtils.update(this);
        if (!requestPermissions()) {
            return;
        }
        initView();
    }

    private void initView() {
        parent = findViewById(R.id.parent);

        spinner = findViewById(R.id.bluetooth_spinner);
        connect = findViewById(R.id.bluetooth_connect);
        seekBar = findViewById(R.id.seek_bar);

        previous = findViewById(R.id.previous);
        play = findViewById(R.id.play);
        next = findViewById(R.id.next);

        volumeHigh = findViewById(R.id.volume_high);
        volumelow = findViewById(R.id.volume_low);
        volumeDisable = findViewById(R.id.volume_disable);

        menu = findViewById(R.id.menu);
        keyboardBounce = findViewById(R.id.keyboard_bounce);
        returnKey = findViewById(R.id.return_key);

        touchBoard = findViewById(R.id.touch_board);

        touchLeft = findViewById(R.id.touch_left);
        touchTop = findViewById(R.id.touch_top);
        touchRight = findViewById(R.id.touch_right);
        touchBottom = findViewById(R.id.touch_bottom);

        editText = findViewById(R.id.edit_text);
        KeyboardInputListener keyboardInputListener = new KeyboardInputListener();
        editText.setFilters(new InputFilter[]{keyboardInputListener});
        editText.setOnKeyListener(keyboardInputListener);

        bluetoothSpinnerAdapter = new BluetoothSpinnerAdapter(getApplicationContext());
        spinner.setAdapter(bluetoothSpinnerAdapter);
        connect.setOnClickListener(new ConnectClickListener(getApplicationContext(), spinner));
        BluetoothUtils.init(getApplicationContext(), bluetoothSpinnerAdapter);

        previous.setOnClickListener(new PreviousClickListener());
        play.setOnClickListener(new PlayClickListener());
        next.setOnClickListener(new NextClickListener());

        volumeHigh.setOnClickListener(new VolumeHighClickListener());
        volumelow.setOnClickListener(new VolumeLowClickListener());
        volumeDisable.setOnClickListener(new VolumeDisableClickListener());

        menu.setOnClickListener(new MenuClickListener());
        keyboardBounce.setOnClickListener(new KeyboardBounceClickListener(getApplicationContext(), editText));
        parent.setOnClickListener(new KeyboardBounceClickListener(getApplicationContext(), editText));
        returnKey.setOnClickListener(new ReturnKeyClickListener());

        AtomicInteger mark = new AtomicInteger(0);
        touchBoard.setOnTouchListener(new TouchBoardListener(seekBar, mark));
        touchBoard.setOnLongClickListener(new TouchBoardLongClickListener(mark));
        touchBoard.setOnClickListener(new TouchBoardClickListener(mark));

        touchLeft.setOnTouchListener(new TouchLeftListener(seekBar));
        touchTop.setOnTouchListener(new TouchTopListener(seekBar));
        touchRight.setOnTouchListener(new TouchRightListener(seekBar));
        touchBottom.setOnTouchListener(new TouchBottomListener(seekBar));
    }

    private boolean requestPermissions() {
        permissionCount++;
        if (permissionCount >= 10) {
            throw new RuntimeException("权限申请失败！");
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            boolean scanPermission = PermissionChecker.checkPermission(this, android.Manifest.permission.BLUETOOTH_SCAN, android.os.Process.myPid(), android.os.Process.myUid(), getPackageName()) != PermissionChecker.PERMISSION_GRANTED;
            boolean advertisePermission = PermissionChecker.checkPermission(this, android.Manifest.permission.BLUETOOTH_ADVERTISE, android.os.Process.myPid(), android.os.Process.myUid(), getPackageName()) != PermissionChecker.PERMISSION_GRANTED;
            boolean connectPermission = PermissionChecker.checkPermission(this, android.Manifest.permission.BLUETOOTH_CONNECT, android.os.Process.myPid(), android.os.Process.myUid(), getPackageName()) != PermissionChecker.PERMISSION_GRANTED;
            if (scanPermission || advertisePermission || connectPermission) {
                ActivityCompat.requestPermissions(this, new String[]{
                        android.Manifest.permission.BLUETOOTH_SCAN,
                        android.Manifest.permission.BLUETOOTH_ADVERTISE,
                        android.Manifest.permission.BLUETOOTH_CONNECT
                }, 1001);
                return false;
            }
        }
        boolean locationPermission = ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED;
        boolean accessPermission = ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED;
        if (locationPermission || accessPermission) {
            ActivityCompat.requestPermissions(this, new String[]{
                    android.Manifest.permission.ACCESS_FINE_LOCATION,
                    android.Manifest.permission.ACCESS_COARSE_LOCATION
            }, 1002);
            return false;
        }
        return true;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 1001:
            case 1002:
                if (!requestPermissions()) {
                    return;
                }
                initView();
        }
    }
}